// StatisticsTab.cpp
#include "statisticstab.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QHeaderView>
#include <QStandardItem>
#include <QSqlQuery>
#include <QSqlRecord>
#include <QSqlError>
#include <QDebug>

StatisticsTab::StatisticsTab(QWidget *parent) : QWidget(parent) {
    modeComboBox = new QComboBox;
    modeComboBox->addItems({"每日统计", "月度汇总"});

    dateEdit = new QDateEdit(QDate::currentDate());
    dateEdit->setDisplayFormat("yyyy-MM-dd");

    queryButton = new QPushButton("查询");
    connect(queryButton, &QPushButton::clicked, this, &StatisticsTab::onQueryClicked);

    tableView = new QTableView;
    tableModel = new QStandardItemModel(this);
    tableView->setModel(tableModel);
    tableView->horizontalHeader()->setStretchLastSection(true);

    summaryLabel = new QLabel("统计信息将显示在这里");

    // 布局设置
    QHBoxLayout *topLayout = new QHBoxLayout;
    topLayout->addWidget(modeComboBox);
    topLayout->addWidget(dateEdit);
    topLayout->addWidget(queryButton);

    QVBoxLayout *mainLayout = new QVBoxLayout;
    mainLayout->addLayout(topLayout);
    mainLayout->addWidget(tableView);
    mainLayout->addWidget(summaryLabel);

    setLayout(mainLayout);
}

void StatisticsTab::onQueryClicked() {
    QString mode = modeComboBox->currentText();
    QDate selectedDate = dateEdit->date();

    if (mode == "每日统计") {
        queryDaily(selectedDate);
    } else {
        queryMonthly(selectedDate);
    }
}

void StatisticsTab::queryDaily(const QDate &date) {
    tableModel->clear();
    tableModel->setHorizontalHeaderLabels({"员工ID", "姓名", "部门", "打卡时间", "类型"});

    QSqlQuery query;
    QString dateStr = date.toString("yyyy-MM-dd");
    query.prepare("SELECT employeeID, name, department, attendaceTime, checkType FROM attendance WHERE date(attendaceTime) = :date ORDER BY attendaceTime ASC");
    query.bindValue(":date", dateStr);

    if (!query.exec()) {
        qWarning() << "查询失败:" << query.lastError().text();
        return;
    }

    int count = 0;
    while (query.next()) {
        QString typeStr = (query.value("checkType").toInt() == 1) ? "上班" : "下班";
        QList<QStandardItem*> rowItems = {
            new QStandardItem(query.value("employeeID").toString()),
            new QStandardItem(query.value("name").toString()),
            new QStandardItem(query.value("department").toString()),
            new QStandardItem(QTime::fromString(query.value("attendaceTime").toString().mid(11, 8), "hh:mm:ss").toString()),
            new QStandardItem(typeStr)
        };
        tableModel->appendRow(rowItems);
        count++;
    }

    updateSummary(QString("共查询到 %1 条记录").arg(count));
}

void StatisticsTab::queryMonthly(const QDate &month) {
    tableModel->clear();
    tableModel->setHorizontalHeaderLabels({"员工ID", "姓名", "正常天数", "迟到", "早退", "缺勤"});

    QString start = month.toString("yyyy-MM-01");
    QString end = month.addMonths(1).toString("yyyy-MM-01");

    QSqlQuery query;
    query.prepare("SELECT employeeID, name, \
                         SUM(CASE WHEN status = 'normal' THEN 1 ELSE 0 END) as 正常, \
                         SUM(CASE WHEN status = 'late' THEN 1 ELSE 0 END) as 迟到, \
                         SUM(CASE WHEN status = 'early' THEN 1 ELSE 0 END) as 早退, \
                         SUM(CASE WHEN status = 'absent' THEN 1 ELSE 0 END) as 缺勤 \
                  FROM attendance \
                  WHERE attendaceTime >= :start AND attendaceTime < :end \
                  GROUP BY employeeID, name");
    query.bindValue(":start", start);
    query.bindValue(":end", end);

    if (!query.exec()) {
        qWarning() << "月度统计查询失败:" << query.lastError().text();
        return;
    }

    int totalPeople = 0;
    int totalDays = 0;

    while (query.next()) {
        int normal = query.value("正常").toInt();
        int late = query.value("迟到").toInt();
        int early = query.value("早退").toInt();
        int absent = query.value("缺勤").toInt();
        totalPeople++;
        totalDays += (normal + late + early);

        tableModel->appendRow({
            new QStandardItem(query.value("employeeID").toString()),
            new QStandardItem(query.value("name").toString()),
            new QStandardItem(QString::number(normal)),
            new QStandardItem(QString::number(late)),
            new QStandardItem(QString::number(early)),
            new QStandardItem(QString::number(absent))
        });
    }

    QString summary = totalPeople > 0 ? QString("本月出勤率约 %1%").arg(totalDays * 100 / (totalPeople * 22)) : "暂无数据";
    updateSummary(summary);
}

void StatisticsTab::updateSummary(const QString &text) {
    summaryLabel->setText(text);
}
